<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/5
 * Time: 9:17
 */
namespace app\home\controller;

use think\Request;
use app\home\controller\Common;
use Endroid\QrCode\QrCode;
use think\Db;
use think\Validate;
use app\yangpay\AlipayLogic;
use think\Log;

/**
 * @title 我的账户信息
 * @description 接口说明
 * @group 樱桃荟
 */

class User extends Common
{
    public $notify_url = '/User/rechargeReback';
    public $return_url = 'http://cherry.guojinkj123.com';
    /**
     *  @title 账户首页展示
     *  @description 首页
     *  @author  田云川
     *  @description 响应数据 头像 昵称  金币数目
     *  @method  GET
     *  @url /home/User/myAccount
     *  @return  nickname:昵称
     *  @return user_gold:  金币数
     *  @return  user_heading:  用户头像
     *  @return  tody_income:  今日收益
     *  @return  all_income:  累计收益
     */
        public function myAccount(Request $request){
            $user = $request->user;
            $arr['nickname']        = $user['user_name'];
            $arr['user_gold']       = $user['user_gold'];
            $arr['user_headimg']    = $user['user_headimg'];
            $arr['user_phone']      = $user['user_phone'];
            $tSnatch   = Db::name('snatch_log')->where([['uid','=',$user['user_id']], ['create_time','>',date('Y-m-d')]])->sum('money');
            $aSnatch   = Db::name('snatch_log')->where(['uid' => $user['user_id']])->sum('money');
            $tbonus    = Db::name('game_log')->where([['user_id', '=', $user['user_id']], ['create_time', '>', date('Y-m-d')], ['type','in','2,3,7']])->sum('compensation');
            $abonus    = Db::name('game_log')->where([['user_id','=',$user['user_id']], ['type','in','2,3,7']])->sum('compensation');
            $tshare    = Db::name('share_profit')->where([['user_id','=',$user['user_id']], ['type','in','1,2,4'], ['create_time','>',date('Y-m-d')]])->sum('money');
            $ashare    = Db::name('share_profit')->where([['user_id','=',$user['user_id']], ['type','in','1,2,4']])->sum('money');
            $arr['tody_income']     = number_format($tSnatch + $tbonus + $tshare,2);
            $arr['all_income']      = number_format($aSnatch + $abonus + $ashare,2); 
            $arr['uid']             = $user['user_id']; 
            return json_success($arr);
        }
        /**
         *  @title 充值记录
         *  @author  田云川
         *  @description 响应数据 时间  金额
         *  @method  POST
         *  @url /home/User/rechargeRecord
         *  @return create_time:  充值时间
         *  @return amount:  充值金额
         */
        public function rechargeRecord(Request $request){
            $user   = $request->user;
            $uid    = $user['user_id'];
            $page   = $request->has('page') ? $request->param('page') : 1;
            $pageN  = $request->has('pageN') ? $request->param('pageN') : 10;
            $rechargeInfo =Db::name('order')->where(['user_id'=>$uid])->field('order_status status,price amount,create_time')->order('pay_time','desc')->paginate($pageN)->each(function($item, $key)
                {
                    $sArr = ['取消','处理中...','成功'];
                    $item['status'] = $sArr[$item['status']];
                    return $item;
                })->toArray();
            // dump(db('order')->getLastSql());die;
            return json_success($rechargeInfo);
        }

        /**
         *  @title 充值
         *  @author  雪飞鸟
         *  @description 充值接口
         *  @method  POST
         *  @url /home/User/dorecharge
         */
        public function dorecharge(Request $request)
        {
            if (!$request->isPost()) return json_error('非法请求');
            $user       = $request->user;
            $moneyN     = $request->param('money');
            $url        = $request->param('url');
            if (!$moneyN || !$url) return json_error('参数不全');
            $selectList = Db::name('config')->value('recharge_money');
            if (!in_array($moneyN, explode(',', $selectList))) return json_error('参数非法');
            $orderNum   = getOrderNum();
            $data       = [
                    'order_number'  => $orderNum,
                    'user_id'       => $user['user_id'],
                    'price'         => $moneyN,
                    'body'          => '充值',
                    'order_status'  => 0,
                    'create_time'   => date('Y-m-d H:i:s'),
                ];
            $oN = Db::name('order')->insert($data);
            if (!$oN) return json_error('充值失败');
            $arr = ['out_trade_no' => $orderNum, 'subject' => '樱桃充值', 'total_amount' => $moneyN, 'body' => '充值', 'passback_params' => $url];
            $pay        = new AlipayLogic('home/yangpay/rechargeReback','home/yangpay/returnRechargeBack?native='.$url);
            $res = $pay->pay($arr);

            // dump($res);
            if ($res) return json_success(['res' => $res]); else return json_error('支付失败');
        }


        /**
         * @title 我的代理
         * @author 田云川
         * @description 响应数据 昵称  账号/推广数  注册时间
         * @method GET
         * @url /home/User/myAgent
         * @return user_name: 用户昵称
         * @return gen_number: 账号/推广人数
         * @return create_time: 时间
         */
        public function myAgent(Request $request){
            $user = $request->user;
            $uid = $user['user_id'];

            $agentInfo = db('user')->where(['user_parent'=>$uid])->select();
            foreach ($agentInfo as $k=>$v){
                $agentInfo[$k]['gen_number'] = $v['user_phone'].'('.db('user')->where(['user_parent'=>$v['user_id']])->count().')';
            }
           return json_success($agentInfo);
        }
        /**
         * @title 个人资料展示
         * @author  田云川
         * @description 响应数据 昵称 账号/手机号  密码  支付宝名称 支付宝账号  身份证号
         * @method GET
         * @url /home/User/perInfoDis
         * @return user_name: 用户昵称
         * @return user_phone: 用户手机号
         * @return user_password: 用户密码
         * @return user_apliy_name: 支付宝名称
         * @return user_apliy_number: 支付宝账号
         * @return number_id: 身份证号
         */
        public function perInfoDis(Request $request){
            $user = $request->user;
            return json_success($user);
        }
    /**
     * @title 提现记录
     * @author  田云川
     * @description 响应数据 类型 金额 时间
     * @method POST
     * @url /home/User/withdRecord
     * @return user_apliy_name: 支付宝名称
     * @return user_apliy_number: 支付宝账号
     * @return amount:            提现金额
     * @return create_time:     操作时间
     * @return status:          状态
     */
    public function withdRecord(Request $request){
        if (!$request->isPost()) return json_error('非法请求'); 
        $user =$request->user;
        $uid = $user['user_id'];
        $page   = $request->has('page') ? $request->param('page') : 1;
        $pageN  = $request->has('pageN') ? $request->param('pageN') : 10;
        if (!$page || !$pageN) return json_error('数据找不到');
        $withdInfo = Db::name('withdraw_order w')->where('w.user_id',$uid)->join('user u','u.user_id=w.user_id')->field('u.user_name uname,u.user_phone uphone,u.user_apliy_name user_apliy_name,u.user_apliy_number user_apliy_number,w.money amount,w.create_time,w.status status,w.type type')->order('create_time','desc')->paginate($pageN)->each(function($item, $key)
            {

                $sArr = ['待审核','已通过','账号错误请检查','成功','失败'];
                $item['status'] = $sArr[$item['status']];
                if ($item['type'] == 1){$item['user_apliy_name'] = $item['uname'];$item['user_apliy_number'] = $item['uphone'];}
                return $item;
            })->toArray();
        if ($withdInfo) return json_success(['data'=>$withdInfo]); else return json_error('没有数据');
    }
    /**
     *  @title 资金记录
     *  @author  田云川
     *  @description 响应数据 状态  时间  金额
     *  @method  POST
     *  @url /home/User/capitalRecord
     *  @return create_time:  充值时间
     *  @return amount:  充值金额
     *  @return status:  状态
     */
    public function capitalRecord(Request $request){
        $user = $request->user;
        $uid = $user['user_id'];
        $page   = $request->has('page') ? $request->param('page') : 1;
        $pageN  = $request->has('pageN') ? $request->param('pageN') : 10;
        if (!$page || !$pageN) return json_error('数据找不到');
        $rechargeInfo =db('share_profit')->where(['user_id'=>$uid,'type'=>3])->field('create_time,money amount,status')->paginate($pageN)->each(function($item, $key)
            {
                $item['amount'] = number_format($item['amount'],2); 
                $item['status'] = $item['status'] == 1 ? '失败' : '成功'; 
                return $item;
            });
        return json_success($rechargeInfo);
    }
    /**
     * @title 提现展示信息页
     * @author 田云川
     * @method GET
     * @url  /home/User/withdDis
     * @return 分润余额:sharePro
     * @return 红包余额:redPacket
     * @return 可提总额:total
     * @return 提现支付宝名称:user_apliy_name
     * @return 提现支付宝账号:user_apliy_number
     * **/
    public function withdDis(Request $request){
        $user = $request->user;
        $uid = $user['user_id'];
        $sharePro =db('share_profit')->where(['user_id'=>$uid,'status'=>1])->sum('money');
        $total = $sharePro+$user['user_gold'];
        $data=[
            'redPacket'=>$user['user_gold'],
            'sharePro' =>$sharePro,
            'total' =>$total,
            'user_apliy_name'=>$user['user_apliy_name'],
            'user_apliy_number'=>$user['user_apliy_number']
        ];
        return json_success($data);
    }
    /**
     * @title 二维码展示
     * @author 田云川
     * @method GET
     * @url /home/User/qrcode
     * @return 邀请码:code
     * **/

    public function qrcode(Request $request)
    {
        $user = $request->user;
        return json_success(['code' => $user['user_reg_code']]);
    }

    /**
     * @title 充值金额列表
     * @author 田云川
     * @method GET
     * @url /home/User/chargeMoney
     * @return chargeInfo:充值列表(数组)
     * **/
    public function chargeMoney(){
        $chargeInfo = db('config')->value('recharge_money');
        $chargeInfo = explode(',',$chargeInfo);
        return json_success($chargeInfo);
    }

    /**
     * @title 添加个人信息
     * @author 雪飞鸟
     * @method POST
     * @url /home/User/addUserMes
     * @param name:user_apliy_name type:string require:1 other: desc:支付宝名
     * @param name:user_apliy_number type:int require:1 other: desc:支付宝号
     * @param name:number_id type:int require:1 other: desc:身份证号
     * @param name:user_name type:string require:0 other: desc:昵称
     * **/
    public function addUserMes(Request $request)
    {
        if (!$request->isPost()) return json_error('非法请求');
        $uId = $request->user['user_id'];
        /*$validate=Validate::make([
            'number_id'=>'min:18',
        ],[
            'user_apliy_name.require'=>'提现支付宝姓名不能为空',
            'user_apliy_number.require'=>'提现支付宝账号不能为空',
            'number_id.require'=>'身份证号不能为空',
            'number_id.min'=>'身份证号最少为18位'
        ]);*/
        $data=[
            'user_apliy_name'=>$request->param('user_apliy_name'),
            'user_apliy_number'=>$request->param('user_apliy_number'),
            'number_id'=>$request->param('number_id'),
        ];
       // $result=$validate->check($data);
       // if (!$result) return json_error($validate->getError());
       $request->has('user_name') && $data['user_name'] = $request->param('user_name');
       $uN = Db::name('user')->where('user_id',$uId)->update($data);
       if ($uN) return json_success('添加成功'); else return json_error('添加失败');
    }


    /**
     * @title 收入记录
     * @author 田云川
     * @method POST
     * @url /home/User/revenueRecord
     * @param name:page type:int require:1 default:1 other: desc:当前第几页
     * @param name:pageN type:int require:1 default:1 other: desc:每页条数
     * @return total:总条数
     * @return current_page:当前页
     * @return per_page:每页条数
     * @return last_page:总页数
     * @return data:消息列表@
     * @data note:类型 money:金额 create_time:时间
     * **/
    public function revenueRecord(Request $request){
            if (!$request->isPost()) return json_error('非法请求');
            $user = $request->user;
            $page = $request->param('page');$pageN = $request->param('pageN');
            $list = Db::name('share_profit')->where('user_id',$user['user_id'])->order('create_time','desc')->paginate($pageN)->toArray();
            if ($list) return json_success($list); else return json_error('没有数据');
    }
    /**
     * @title 游戏记录
     * @author 田云川
     * @url /home/User/gamelog
     * @Url GET
     * @param name:page type:int require:1 default:1 other: desc:当前第几页
     * @param name:pageN type:int require:1 default:1 other: desc:每页条数  
     * @return room_name:房间名称(新手区1)
     * @return odds:赔率(1.5);
     * @return gold_range:规则(20-50/十币五包);
     * @return snatch_money:抢到的金额
     * @return room_type:类型(扫雷/接龙)
     * @return type:记录类型(埋雷/幸运/幸运)
     * @return compensation:踩雷赔付/发雷奖励/埋雷金额
     * @return create_time:时间
     * **/
    public function gamelog(Request $request){
        if (!$request->isPost()) return json_error('非法请求'); 
        $user   = $request->user;
        $uid    = $user['user_id'];
        $page   = $request->param('page');
        $pageN  = $request->param('pageN');
        if (!$page || !$pageN) return json_error('数据找不到');
        $list   = Db::name('game_log g')->where('g.user_id',$user['user_id'])->join('ch_room r','g.room_id = r.room_id')->field('r.room_name,r.type room_type,r.gold_range,r.odds,g.user_id sid,g.comp_id sendid,g.type type,g.compensation compensation,g.snatch_money snatch_money,g.create_time')->order('g.create_time','desc')->paginate($pageN)->each(function($item, $key){
                if ($item['type'] == 4) {$item['compensation'] = $item['snatch_money'];}
                $typeArr = ['踩雷赔付','幸运','埋雷奖','红包退回','埋雷','手气最差','发雷赔付','抢红包'];
                
                $item['type'] = $typeArr[$item['type']-1];
                return $item;
            })->toArray();
        if ($list) return json_success($list); else return json_error('没有数据');
    }
    /**
     * @title 游戏规则
     * @author 田云川
     * @url /home/User/gameRule
     * @POST
     * @param name:room_id type:int require:1 default:1 other: desc:房间id
     * @return gold:用户金币数
     * @return gameIntro:游戏说明
     * **/
    public function gameRule(Request $request)
    {
        $user =$request->user;
        $room_id =$request->post();
        $gold = db('user')->where(['user_id'=>$user['user_id']])->value('user_gold');
        $gameIntro = db('room')->where(['room_id'=>$room_id['room_id']])->value('game_intro');
        $data = [
            'gold'=>$gold,
            'gameIntro'=>$gameIntro
        ];
        return json_success($data);
    }
    /**
     * @title 提现申请
     * @author 田云川
     * @method POST
     * @url /home/User/cashWithApli
     * @param name:price type:string require:1 other: desc:提现金额
     * @param name:type type:int require:1 other: desc:提现方式 1--红包游戏，2--支付宝
     * 
     **/
    public function cashWithApli(Request $request)
    {
        if (!$request->isPost()) return json_error('非法请求'); 
        $user = $request->user;
        $data = $request->post();
        if (array_key_exists('type', $data) && $data['type'] ==1) 
        {
            $sU = Db::name('share_profit')->where(['user_id' => $user['user_id'], 'status' => 1])->sum('money');
            if ($sU != $data['price']) return json_error('提现失败1');
            Db::startTrans();
            try {
                $sN     = Db::name('share_profit')->where('user_id',$user['user_id'])->update(['status' => 0]);
                if (!$sN) {Db::rollback();return json_error('提现失败3');}
                $sArr = [
                    'user_id'       => $user['user_id'],
                    'type'          => 3,
                    'note'          => '合并提现',
                    'money'         => $sU,
                    'create_time'   => date('Y-m-d H:i:s'),
                    'status'        => 0,
                ];
                $addN   = Db::name('share_profit')->insert($sArr);
                if (!$addN) {Db::rollback();return json_error('提现失败4');}
                $oArr = [
                    'user_id'       => $user['user_id'],
                    'money'         => $sU,
                    'status'        => 3,
                    'type'          => 1,
                    'create_time'   => date('Y-m-d H:i:s'),
                ];
                $oN = Db::name('withdraw_order')->insert($oArr);
                if (!$oN) {Db::rollback();return json_error('提现失败4');}
                Db::commit();
                return json_success('提现成功');
            } catch (Exception $e) {
                Db::rollback();
                return json_error('提现失败5');
            }
        }
        else if (array_key_exists('type', $data) && $data['type'] == 2)
        {
            if (!$user['user_apliy_name'] || !$user['user_apliy_number'] || !$user['number_id']) return json_error('请先完善支付宝信息');
            $cInfo = Db::name('config')->find();
            $lowM = $cInfo['low_money'];
	
            if ($data['price'] < $lowM || $data['price'] % 20 != 0) return json_error('提现金额不能小于 '.$lowM.' 并是20的倍数');
            $sMoney = $user['user_gold'];
            if($data['price'] > $sMoney) return json_error('账户余额不足');
            $actualMoney = $data['price'] * (1 - $cInfo['withdraw_poundage']/100);
            /*Db::startTrans();
            try {
                $uN = Db::name('user')->where(['user_id' => $user['user_id']])->setDec('user_gold',$data['price']);
                return json_success("$uN");
                if(!$uN){
                    Db::rollback();
                }
                

                $oArr = [
                    'user_id'       => $user['user_id'],
                    'order_number'  => getOrderNumber('withdraw_order'),
                    'money'         => $data['price'],
                    'arrival_money' => $actualMoney,
                    'status'        => 0,
                    'type'          => 2,
                    'create_time'   => date('Y-m-d H:i:s'),
                ];
                $oN = Db::name('withdraw_order')->insert($oArr);
               
                    Db::commit();
                    return json_success('订单提交成功11');
               
            } catch (Exception $e) {
                Db::rollback();
                return json_error('订单提交失败5');
            }*/



            $uN = Db::name('user')->where(['user_id' => $user['user_id']])->setDec('user_gold',$data['price']);

            if (!$uN) return json_error('订单提交失败1');
            
            $oArr = [
                'user_id'       => $user['user_id'],
                'order_number'  => getOrderNumber('withdraw_order'),
                'money'         => $data['price'],
                'arrival_money' => $actualMoney,
                'status'        => 0,
                'type'          => 2,
                'create_time'   => date('Y-m-d H:i:s'),
            ];
            $oN = Db::name('withdraw_order')->insert($oArr);
            if (!$oN) {
                return json_error('订单提交失败2');
            }
            return json_success('订单提交成功');
        }else{return json_error('非法请求');}
    }

    /**
     * @title 获取提现最低金额
     * @author 田云川
     * @method POST
     * @url /home/User/getLowMoney
     * 
     **/
    public function getLowMoney(Request $request)
    {
        if(!$request->isPost()) return json_error('非法请求');
        $cInfo = Db::name('config')->find();
        if($cInfo) return json_success(['low_money' => $cInfo['low_money']]); else return json_error('数据访问错误');
    }

    /**
     * @title 获取房间名
     * @author 田云川
     * @method POST
     * @url /home/User/getRoomInfo
     * @param name:roomId type:int require:1 other: desc:房间id
     * 
     **/
    public function getRoomInfo(Request $request)
    {
        if(!$request->isPost()) return json_error('非法请求');
        $id = $request->param('roomId');
        $rInfo = Db::name('room')->where('room_id',$id)->find();
        if($rInfo) return json_success($rInfo); else return json_error('数据访问错误');
    }

    /**
    * @title 登出
    * @description 登出
    * @author zjj
    * @url /home/User/logout
    * @method POST
    * @header name:token require:1 default: desc:token
    */
    public function logout(Request $request)
    {
        $uid  = $request->user['user_id'];
        Db::name('user')->where('user_id',$uid)->setField('user_token','');
        return json_success('退出成功');
    }
  
  	/**
    * @title 用户信息
    * @description 用于房间
    * @author zjj
    * @url /home/User/uInfo
    * @method POST
    * @header name:token require:1 default: desc:token
    * @return uid:用户id
    * @return uGold:游戏余额
    */
    public function uInfo(Request $request)
    {
        if(!$request->isPost()) return json_error('非法请求');
        $uid    = $request->user['user_id'];
        $ugold  = $request->user['user_gold'];
        $uInfo  = ['uid' => $uid,'uGold' => $ugold];
        if($uInfo) return json_success($uInfo); else return json_error('获取信息失败');
    }

    public function test(Request $request)
    {
        $str = ',95,109,115,117,118,119,120,121,122,123,124';
        $pIds       = array_reverse(explode(',', substr($str,1)));
        dump($pIds);
        $someIds    = array_slice($pIds, 0, 3);
        dump($someIds);
    }
}
